package com.sixfoot.service;

import com.sixfoot.dao.UserRepository;
import com.sixfoot.domain.Permission;
import com.sixfoot.domain.Role;
import com.sixfoot.domain.User;
import com.sixfoot.facade.user.UserDto;
import com.sixfoot.facade.user.UserInputArgs;
import com.sixfoot.foundation.mapping.service.DtoPagingService;
import com.sixfoot.foundation.rest.ErrorCodeException;
import com.sixfoot.foundation.utils.SystemErrorCodes;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserService extends DtoPagingService<User, UserDto, UserInputArgs, String> {

	public User findByUsername(String username) {
		return ((UserRepository) super.getRepository()).findByUsername(username);
	}

	public List<String> findRoleIdsById(String id) {
		User user = ((UserRepository) super.getRepository()).findOne(id);
		Set<Role> userRoles = user == null ? new HashSet<>() : user.getRoles();
		List<String> roleIds = userRoles.stream().map(Role::getId).collect(Collectors.toList());
		return roleIds;
	}
	
	public List<String> loadRoles(String username) {
		List<String> roles = new ArrayList<String>();
		User user = findByUsername(username);
		if (user.getRoles() != null) {
			for (Role r : user.getRoles()) {
				roles.add(r.getCode());
			}
		} else
			throw new AuthorizationException("没有角色");
		return roles;
	}

	public List<String> loadPermissions(String username) {
		List<String> permissions = new ArrayList<String>();
		User user = findByUsername(username);
		if (user.getRoles() != null) {
			for (Role r : user.getRoles()) {
				if (r.getPerms() != null) {
					for (Permission p : r.getPerms()) {
						permissions.add(p.getCode());
					}
				}
			}
		} else
			throw new AuthorizationException("没有权限");
		return permissions;
	}
	
	public void updatePassword(String username, String password) {
		User user = findByUsername(username);
		if (user == null) {
			throw new ErrorCodeException(SystemErrorCodes.NOUSER);
		}
		user.setPassword(password);
		((UserRepository) super.getRepository()).save(user);
	}
}